package com.example.singing.manager;

import com.example.singing.model.Team;
import com.example.singing.util.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 队伍管理类
 */
public class TeamManager {
    private List<Team> teams;
    private static final String TEAM_FILE = "teams.dat";

    public TeamManager() {
        this.teams = new ArrayList<>();
        loadTeams();
        // 移除示例数据，不再自动添加
    }

    /**
     * 添加队伍
     */
    public void addTeam(Team team) {
        teams.add(team);
        saveTeams();
    }

    /**
     * 根据ID获取队伍
     */
    public Team getTeamById(String id) {
        for (Team team : teams) {
            if (team.getId().equals(id)) {
                return team;
            }
        }
        return null;
    }

    /**
     * 获取所有队伍
     */
    public List<Team> getAllTeams() {
        return new ArrayList<>(teams);
    }

    /**
     * 更新队伍
     */
    public void updateTeam(Team updatedTeam) {
        for (int i = 0; i < teams.size(); i++) {
            if (teams.get(i).getId().equals(updatedTeam.getId())) {
                teams.set(i, updatedTeam);
                saveTeams();
                return;
            }
        }
    }

    /**
     * 删除队伍
     */
    public boolean deleteTeam(String id) {
        System.out.println("尝试删除队伍ID: " + id);
        System.out.println("删除前队伍总数: " + teams.size());
        
        boolean removed = teams.removeIf(t -> {
            boolean shouldRemove = t.getId().equals(id);
            if (shouldRemove) {
                System.out.println("找到要删除的队伍: " + t.getId() + ", 名称: " + t.getName());
            }
            return shouldRemove;
        });
        
        System.out.println("删除操作结果: " + removed);
        System.out.println("删除后队伍总数: " + teams.size());
        
        if (removed) {
            try {
                saveTeams();
                System.out.println("队伍数据已保存到文件");
            } catch (Exception e) {
                System.err.println("删除队伍后保存数据失败: " + e.getMessage());
                e.printStackTrace();
            }
        }
        return removed;
    }
    
    /**
     * 删除队伍（带级联删除评分）
     */
    public boolean deleteTeamWithCascade(String id, com.example.singing.manager.ScoreManager scoreManager) {
        System.out.println("尝试级联删除队伍ID: " + id);
        
        // 先删除相关的评分数据
        if (scoreManager != null) {
            List<com.example.singing.model.Score> relatedScores = scoreManager.getScoresByTeamId(id);
            System.out.println("找到相关评分数量: " + relatedScores.size());
            
            for (com.example.singing.model.Score score : relatedScores) {
                boolean scoreDeleted = scoreManager.deleteScoreById(score.getId());
                System.out.println("删除评分 " + score.getId() + " 结果: " + scoreDeleted);
            }
        }
        
        // 再删除队伍
        return deleteTeam(id);
    }

    /**
     * 保存队伍数据
     */
    public void saveTeams() {
        FileUtil.saveData(teams, TEAM_FILE);
    }

    /**
     * 加载队伍数据
     */
    @SuppressWarnings("unchecked")
    public void loadTeams() {
        Object data = FileUtil.loadData(TEAM_FILE);
        if (data != null) {
            teams = (List<Team>) data;
        }
    }

    /**
     * 添加示例数据
     */
    private void addSampleData() {
        System.out.println("开始创建示例队伍数据...");
        
        // 创建示例队伍
        Team team1 = new Team("TEAM_SAMPLE_001", "星光合唱团", Arrays.asList("张三", "李四", "王五"), "13800138000");
        team1.setCompetitionId("COMP001"); // 关联到示例比赛1
        System.out.println("创建队伍1: " + team1.getName() + ", 比赛ID: " + team1.getCompetitionId());
        
        Team team2 = new Team("TEAM_SAMPLE_002", "天籁之音", Arrays.asList("赵六", "钱七", "孙八"), "13900139000");
        team2.setCompetitionId("COMP001"); // 关联到示例比赛1
        System.out.println("创建队伍2: " + team2.getName() + ", 比赛ID: " + team2.getCompetitionId());
        
        // 添加李凯java大王队伍
        Team team4 = new Team("TEAM_SAMPLE_004", "李凯java大王", Arrays.asList("李凯", "Java", "大王"), "13600136000");
        team4.setCompetitionId("COMP001"); // 关联到示例比赛1
        System.out.println("创建队伍4: " + team4.getName() + ", 比赛ID: " + team4.getCompetitionId());
        
        // 添加到列表
        teams.add(team1);
        teams.add(team2);
        teams.add(team4);
        
        System.out.println("示例队伍创建完成，总数: " + teams.size());
        saveTeams();
    }
    
    /**
     * 生成唯一的队伍ID
     */
    public String generateTeamId() {
        // 使用时间戳和随机数生成唯一ID，避免与示例数据冲突
        return "TEAM_" + System.currentTimeMillis() + "_" + (int)(Math.random() * 1000);
    }
}